<?php 
class Login extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper(array('email'));
        $this->load->model('advert_model', 'advert');
        $this->load->model('user_model', 'user');
        $this->load->model('user_related_self_model', 'user_related_self');
    }
    
    public function index()
    {
        if ($this->frontUser && $this->userType & UTID_PROVIDER) {
            $this->redirect($this->config->gongying_url);
        } else if ($this->frontUser) {
            $this->redirect($this->config->wap_base_url);
        }
        if (isset($_SERVER['HTTP_REFERER'])) {
            $parseUrl = parse_url($_SERVER['HTTP_REFERER']);
            if (isset($parseUrl['query']) && strpos($parseUrl['query'], 'backurl') !== false) {
                $this->data['backurl'] = urldecode(strstr($parseUrl['query'], 'http'));
            } else {
                $this->data['backurl'] = $_SERVER['HTTP_REFERER'];
            }
        } else {
            $this->data['backurl'] = $this->config->gongying_url;
        }
        $this->data['captcha'] = $this->getCaptcha();
        $this->data['err_count'] = get_cookie('err_count');
        $res = $this->advert->findByParams(['status'=> 1, 'opentype' => 'link', 'position' => 2, 'provider_id' => $this->providerUid], '*', null, 'sort ASC')->row_array();
        $this->data['login_bg'] = isset($res['picture']) ? $this->config->show_image_url($res['picture']) : '/skins/images/login-bg1.jpg';
        $this->load->view('login/newindex', $this->data);
    }
    
    /**
     * 登录提交页面
     */
    public function loginPost()
    {
        $d = $this->input->post();

        //会员登录
        if (!empty($d['act']) && $d['act'] == 1) {
            $err_count = get_cookie('err_count');
            //验证码验证
            if ($err_count > 3) {
                if (strtoupper($d['captcha']) != strtoupper(get_cookie('captcha'))) {
                    $this->ajaxJson(['status' => false, 'msg' => '验证码不正确', 'input' => 'captcha']);
                }
            }
            $result = $this->user->login($d);
            if ($result->num_rows() <= 0) {
                set_cookie('err_count', $err_count + 1, 43200);
                $this->ajaxJson(['status' => false, 'msg' => '用户名或密码错误', 'data' => $err_count]);
            }
            $user = $result->row();
            if (!($user->user_type&UTID_PROVIDER)) {
                set_cookie('err_count', $err_count + 1, 43200);
                $this->ajaxJson(['status' => false, 'msg' => '当前非供应商账号~', 'data' => $err_count]);
            }
            if ($user->flag == 2) {
                set_cookie('err_count', $err_count + 1, 43200);
                $this->ajaxJson(['status' => false, 'msg' => '此帐号已被冻结，请与管理员联系', 'data' => $err_count]);
            }
            delete_cookie('err_count');
        //快捷登录
        } else {
            $user = $this->user->quick_login($d);
            if (!($user->user_type&UTID_PROVIDER)) {
                set_cookie('err_count', $err_count + 1, 43200);
                $this->ajaxJson(['status' => false, 'msg' => '当前非供应商账号~', 'data' => $err_count]);
            }
            if ($user->flag == 2) {
                $this->ajaxJson(['status' => false, 'msg' => '此帐号已被冻结，请与管理员联系']);
            }
        }
        
        $this->user->visitCount($user->uid); //统计用户登录次数。
        $userType = $this->usertype($user->user_type);
        $session = array(
            'ACT_UID'        => $user->uid,
            'ACT_UTID'       => $user->user_type,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => $user->extra,
            'ALIAS_NAME'     => urlencode($user->alias_name),
            'OWNER_ID'       => $user->uid,
            'OWNER_NAME'     => $user->user_name,
            'PARENT_ID'      => $user->parent_id,
            'PERSONAL_PHOTO' => urlencode($user->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 3 * 24 * 3600);
        $this->cache->memcached->save('frontUser', serialize($session), 3 * 24 * 3600);
        if (($user->user_type & UTID_PROVIDER) || ($user->user_type & UTID_TELLER)) {
            $directUrl = $this->config->gongying_url;
        } else if ($this->input->post('backurl')) {
            $directUrl = $this->input->post('backurl');
        } else {
            $directUrl = $this->config->gongying_url;
        }

        $this->ajaxJson(['status' => true, 'msg' => $directUrl]);
    }
    
    /**
     * 退出登陆
     */
    public function logout()
    {
        if (get_cookie('frontUser')) {
            delete_cookie('frontUser');
        }
        if (get_cookie('bz_session')) {
            delete_cookie('bz_session');
        }
        $this->cache->memcached->delete('frontUser');
        $this->redirect(site_url('login/index'));
    }
    
    /**
     * 验证登录页手机动态码
     * cyl
     */
    public function checkPhone()
    {
        $phone = $this->input->post('phone');
        $captcha = $this->input->post('captcha');
    
        if (strtoupper($captcha) != strtoupper(get_cookie('captcha'))) {
            $this->ajaxJson(false, '验证码不正确');
        }
        if (!valid_mobile($phone)) {
            $this->ajaxJson(false, '手机号码有误');
        }

        return $this->sendCommonSms($phone, 'SMS_135430024');
    }
    
    /**
     *  账户切换
     */
    public function userSwitch()
    {
        $callback = $this->input->get('callback');
        $data['userRelated'] = array();
        if (!$this->frontUser) {
            $jsonData =json_encode(array(
                'status' => FALSE,
                'msg'    => '账号登陆已失效'
            ));
            die($callback.'(' . $jsonData . ')');
        }
        $loginUser = array(
            'uid'           => $this->uid,
            'userType'      => $this->userType,
            'userName'      => $this->userName,
            'aliasName'     => $this->aliasName,
            'userTypeEn'    => $this->userTypeEn,
            'userTypeName'  => $this->userTypeName,
            'userParentId'  => $this->userParentId,
            'personalPhoto' => $this->personalPhoto
        );
        $data['userRelated'] = $this->getUserRelated();
        array_unshift($data['userRelated'], $loginUser); //讲数组数据插入到数组之前
        $jsonData = json_encode(array(
            'status' => 1,
            'msg'    => $this->load->view('login/userSwitch', $data, TRUE)
        ));
        die($callback.'(' . $jsonData . ')');
    }
    
    public function getUserRelated()
    {
        $userRelated = array();
        if ($this->userType&UTID_PROVIDER) {
            $result = $this->user_related_self->providerFxReult($this->uid);
        } else {
            $result = $this->user_related_self->resellerFxReult($this->uid);
        }
        if ($result->num_rows() <= 0) {
            return $userRelated;
        }
        //获取关联用户Uid
        $uidArr = array();
        foreach ($result->result() as $item) {
            if ($this->userType&UTID_PROVIDER) {
                $uidArr['uid'][] = $item->reseller_uid;
            } else {
                $uidArr['uid'][] = $item->provider_uid;
            }
        }
        if (empty($uidArr)) {
            return $userRelated;
        }
        //获取关联数据用户信息
        $result1 = $this->user->findByIds($uidArr);
        if ($result1->num_rows() <= 0) {
            return $userRelated;
        }
        foreach ($result1->result() as $user) {
            $userInfo = $this->usertype($user->user_type);
            $userRelated[] = array(
                'uid'           => $user->uid,
                'userType'      => $user->user_type,
                'userName'      => $user->user_name,
                'aliasName'     => $user->alias_name,
                'userTypeEn'    => $userInfo['type_en'],
                'userTypeName'  => $userInfo['type_zh'],
                'userParentId'  => $user->parent_id,
                'personalPhoto' => $user->personal_photo
            );
        }
        return $userRelated;
    }
    
    //用户切换直接登陆
    public function userSwitchLogin()
    {
        $uid = $this->input->get('uid');
        $callback = $this->input->get('callback');
        if (!$res = $this->user->findOne(['uid' => $uid])->row()) {
            $jsonData = json_encode(array(
                'status' => FALSE,
                'msg'    => '账号密码错误'
            ));
            die($callback.'(' . $jsonData . ')');
        }
        if ($res->flag == 2) {
            $jsonData = json_encode(array(
                'status' => FALSE,
                'msg'    => '该账号已经冻结'
            ));
            die($callback.'(' . $jsonData . ')');
        }
        $userType = $this->usertype($res->user_type);
        $session = array(
            'ACT_UID'        => $res->uid,
            'ACT_UTID'       => $res->user_type,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => $res->extra,
            'ALIAS_NAME'     => urlencode($res->alias_name),
            'OWNER_ID'       => $res->uid,
            'OWNER_NAME'     => $res->user_name,
            'PARENT_ID'      => $res->parent_id,
            'PERSONAL_PHOTO' => urlencode($res->personal_photo),
        );
        $cookie_time = 3 *24 * 3600;
        set_cookie('frontUser', serialize($session), $cookie_time);
        $this->cache->memcached->save('frontUser', serialize($session), $cookie_time);
        if (($res->user_type & UTID_PROVIDER) || ($res->user_type & UTID_TELLER)) {
            $url = $this->config->gongying_url;
        } else {
            $url = $this->config->wap_base_url.$this->providerUid;
        }
        $jsonData = json_encode(array(
            'status' => TRUE,
            'msg'    => $url
        ));
        die($callback.'(' . $jsonData . ')');
    }
}